package com.boboPlanet.comm.filestorage;

import cn.xuyanwu.spring.file.storage.FileInfo;
import com.alibaba.fastjson.JSON;
import com.boboPlanet.comm.entity.po.FileDetailPO;
import com.boboPlanet.comm.exception.BusinessException;
import com.boboPlanet.comm.rabbitmq.PlanetCommMQEnum;
import com.boboPlanet.comm.rabbitmq.PlanetMqProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @Description: TODO 星球文件上传与下载,基于springboot原生
 * @Author: mis_wu
 * @Date: 2023/7/10
 * @Company planet
 **/
@Slf4j
@Component
public class PlanetFileBaseTemplate {

    private static final String SPLIT_STR = ".";
    private static final String file_prefix = "planet";

    @Value("${spring.planet.file.upload.base-path}")
    private String basePath;

    @Value("${spring.planet.file.root-path}")
    private String rootPath;

    @Value("${spring.file-storage.default-platform}")
    private String defaultPlatForm;


    @Resource
    private PlanetMqProducer producer;

    /**
     * 文件上传
     * @param originFile 源文件
     * @param fileName 自定义文件名,可为空[建议空,如果自定义可能会重复造成重名文件覆盖]
     * @throws IOException E
     */
    public void upload(MultipartFile originFile,String fileName) throws IOException {
        if (originFile == null){
            throw BusinessException.build("上传文件不能为空,请重新上传");
        }

        String originName = originFile.getOriginalFilename();
        //获取文件后缀
        assert originName != null : "源文件名称不能为空";
        String suffix = originName.substring(originName.lastIndexOf(SPLIT_STR));
        //尽量重新生成文件名,避免文件名重复被覆盖
        if (StringUtils.isBlank(fileName)){
            fileName = file_prefix + UUID.randomUUID() + suffix;
        }

        assert StringUtils.isNotBlank(basePath) : "上传文件地址不存在,请配置有效的上传地址";
        File file = new File(basePath + rootPath);
        if (!file.exists()){
            boolean mkdir = file.mkdir();
            log.info("create new file path,base path is: {}, mkdir:{}",basePath + rootPath,mkdir);
        }

        originFile.transferTo(new File(basePath + rootPath + fileName));

        //存储到数据库
        FileInfo fileInfo = new FileInfo();
        fileInfo.setUrl(basePath + rootPath + fileName);
        fileInfo.setFilename(fileName);
        fileInfo.setBasePath(basePath);
        fileInfo.setPlatform(defaultPlatForm);
        fileInfo.setPath(rootPath);
        Map<String, Object> resultMap = FileDetailPO.buildFileInfo(fileInfo);
        FileDetailPO fileDetailPO = (FileDetailPO) resultMap.get(FileDetailPO.MAP_KEY_3);

        producer.sendMsg(PlanetCommMQEnum.PLANET_SAVE_FILE_MQ, JSON.toJSONString(fileDetailPO));

    }
}
